package drds.plus.rule_engine.utils;

import drds.plus.common.model.comparative.Comparative;
import drds.plus.rule_engine.column_value_enumerator.Enumerator;
import drds.plus.rule_engine.column_value_enumerator.EnumeratorImpl;
import drds.plus.rule_engine.rule.RangeRuleColumn;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class RuleUtils {

    private static final Enumerator enumerator = new EnumeratorImpl();

    /**
     * 返回对应column的枚举值
     */
    public static Map<String, Set<Object>> getSamplingField(Set<RangeRuleColumn> rangeRuleColumnSet, Map<String, Comparative> columnNameToComparativeMap) {
        // 枚举以后的columns与他们的描点之间的对应关系
        Map<String, Set<Object>> enumeratedMap = new HashMap<String, Set<Object>>(rangeRuleColumnSet.size());
        for (RangeRuleColumn rangeRuleColumn : rangeRuleColumnSet) {
            String columnName = rangeRuleColumn.columnName;
            // 当前enumerator中指定当前规则是否需要处理交集问题。
            try {
                if (columnNameToComparativeMap.containsKey(columnName)) {
                    Set<Object> valueSet = enumerator.enumerateValue(columnNameToComparativeMap.get(columnName), rangeRuleColumn.cumulativeTimes, rangeRuleColumn.atomicIncreateValue, rangeRuleColumn.needMergeValueInCloseInterval);
                    enumeratedMap.put(columnName, valueSet);
                } else {
                    // 如果sql中不存在，则进行全表扫
                    enumeratedMap.put(columnName, rangeRuleColumn.enumerateRange());
                }
            } catch (UnsupportedOperationException e) {
                throw new UnsupportedOperationException("当前列分库分表出现错误，出现错误的列名是:" + rangeRuleColumn.columnName, e);
            }
        }

        return enumeratedMap;
    }

    public static <T> T cast(Object object) {
        return (T) object;
    }
}
